package com.cn.util;

import com.cn.service.NewsService;
import com.cn.vo.CommtypeImg;
import com.cn.voservice.CommtypeImgService;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.SQLException;
import java.util.*;

@WebListener
public class IndexShow implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        CommtypeImgService cs = new CommtypeImgService();
        NewsService ns = new NewsService();
        Map<String, List<CommtypeImg>> map = new LinkedHashMap<>();
        List<CommtypeImg> meau = null;
        try {
            meau = cs.queryAll();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        List<CommtypeImg> meau2 = new ArrayList<CommtypeImg>();
        List<CommtypeImg> list3 = new ArrayList<CommtypeImg>();
        Map<String, CommtypeImg> allCate = new LinkedHashMap<>();
        Map<String, List<CommtypeImg>> map1 = new LinkedHashMap<>();
        for (CommtypeImg category : meau) {
            String parent_id = category.getFather_id();
            if (map.containsKey(parent_id)) {
                List<CommtypeImg> list = map.get(parent_id);
                list.add(category);
                map.put(parent_id, list);
            } else {
                List<CommtypeImg> list = new ArrayList<>();
                list.add(category);
                map.put(parent_id, list);
            }


            if (parent_id.equals("0")) {
                meau2.add(category);
            }

            allCate.put(category.getCommodity_type_id(), category);

        }

        System.out.println(meau.size());
        System.out.println(meau2.size());
        ServletContext application = servletContextEvent.getServletContext();
        try {
            application.setAttribute("news", ns.queryAll());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        application.setAttribute("meau", meau2);
        application.setAttribute("meaumap", map);
        application.setAttribute("allCate", allCate);
        application.setAttribute("meau3", meau);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
